# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

myStartsWith <- function(str, prefix){
    substring(str, 1, nchar(prefix)) == prefix
}

library(optparse)
library(ropls)
library(magrittr)
library(RColorBrewer)
library(scales)
library(tidyverse)

option_list <- list(
make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--mc", default = "meta_color.txt", type = "character", help = "metabolite color file"),
make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
make_option("--cp", default = "", type = "character", help = "compare info ")
)
opt <- parse_args(OptionParser(option_list = option_list))

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
select(c("SampleID", "ClassNote"))

sampleIds <- sampleInfo %>%
.$SampleID

data <- read_csv(opt$i) %>%
    select(- c("HMDB", "KEGG", "Metabolite")) %>%
    select(c("Class", sampleIds))
data

noOthersDf <- data %>%
    group_by(Class) %>%
    summarise_all(sum) %>%
    rowwise() %>%
    do({
        result <- as.data.frame(.)
        data <- result[1, sampleIds]
        result$sum <- sum(data)
        result
    }) %>%
    ungroup() %>%
    select(c("Class", "sum")) %>%
    mutate(percent = sum * 100 / (sum(sum)))

df <- noOthersDf %>%
    rowwise() %>%
    do({
        result <- as.data.frame(.)
        percent <- result[1, "percent"]
        class <- result[1, "Class"] %>% as.character()
        newClass <- ifelse(percent < 2, "Others", class)
        result$Class <- newClass
        result
    }) %>%
    group_by(Class) %>%
    summarise_all(sum) %>%
    arrange(desc(percent)) %>%
    mutate(percent = round(percent, 2)) %>%
    mutate(rate = percent / 100, label = str_c(Class, " ", percent, "%"))

df

colorData <- read_tsv(opt$mc) %>%
    select(c("Class", "col")) %>%
    rbind(c("Others", "#0077CC"))

head(colorData)

dfc <- df %>%
left_join(colorData, by = c("Class"))

outDf <- noOthersDf %>%
    arrange(desc(percent)) %>%
    select(c("Class", "percent")) %>%
    rename(`percent(%)` = percent)
noOthersDf
write_csv(outDf, "Class_Pieplot.csv")

head(dfc)

opar <- par(no.readonly = TRUE)
charN <- dfc$label %>%
nchar() %>%
max
lrM <- charN * 0.03
width <- charN * 0.06 + 7
pdf("Class_Pieplot.pdf", width = width, height = 5)
par(mar = c(0.5, 0, 0.5, 0) + 0.1, family = "Times")

pie(dfc$percent, labels = dfc$label, clockwise = TRUE, radius = 0.9, col = dfc$col,
border = "white", init.angle = 0, main = "")
par(opar)

dev.off()
